﻿using System;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using RapidDownloader.Model.Helpers;

namespace RapidDownloader.Model
{
    public static class WebHelper
    {
        public static string DownloadString(string address)
        {
            return new WebClient().DownloadString(address);
        }

        public static IObservable<byte[]> AsyncRead(this Stream stream, int bufferSize)
        {
            var downloader = new DownloadSubject();

            Task.Factory.StartNew(() =>
                {
                    try
                    {
                        var buffer = new byte[bufferSize];
                        int downloaded;
                        while (!downloader.IsDisposed && DownloadLimiter.Limit(downloaded = stream.Read(buffer, 0, bufferSize)))
                        {
                            var downloadedBytes = new byte[downloaded];
                            Array.Copy(buffer, downloadedBytes, downloaded);
                            downloader.OnNext(downloadedBytes);
                        }
                    }
                    catch (Exception ex)
                    {
                        downloader.OnError(ex);
                    }

                    downloader.OnCompleted();
                }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);

            return downloader;
        }

        public static Stream WithOptionalDebug(this Stream stream, long size)
        {
#if DEBUG
            return new DebugStream(stream, size);
#else
            return stream;
#endif
        }
    }
}